#include "TextureManager.h"

unsigned int TextureManager::loadTexture( std::string fileName ) throw ( TextureNotFoundException )
{
    Texture texture;

    texture.m_fileName = fileName;
    texture.m_textureSurface = IMG_Load( fileName.c_str() );
    if( texture.m_textureSurface == NULL )
    {
        throw TextureNotFoundException( fileName );
    }

    glGenTextures( 1, &(texture.m_textureID) );
    glBindTexture( GL_TEXTURE_2D, texture.m_textureID );
    if( texture.m_textureSurface->format->BitsPerPixel == 32 )
    {
        glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, texture.m_textureSurface->w, texture.m_textureSurface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.m_textureSurface->pixels );
    }
    else
    {
        glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, texture.m_textureSurface->w, texture.m_textureSurface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, texture.m_textureSurface->pixels );
    }

    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

    return texture.m_textureID;
}

unsigned int TextureManager::getTexture( std::string fileName ) throw ( TextureNotFoundException )
{
    for(unsigned int i = 0; i < m_textures.size(); ++i)
    {
        if( m_textures[ i ].m_fileName == fileName )
        {
            return i;
        }
    }
    return loadTexture( fileName );
}
